package com.mes.cloud.service;

import com.mes.cloud.api.dto.request.role.BindMenuRequest;
import com.mes.cloud.api.dto.request.role.MenuListRequest;
import com.mes.cloud.api.dto.request.role.RolePidListRequest;
import com.mes.cloud.api.dto.response.role.RoleMenuDto;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.dao.SysMenuDao;
import com.mes.cloud.dao.SysRoleDao;
import com.mes.cloud.dao.SysRoleMenuDao;
import com.mes.cloud.entity.SysMenu;
import com.mes.cloud.entity.SysRole;
import com.mes.cloud.entity.SysRoleMenu;
import com.mes.cloud.entity.vo.role.MenuVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 角色菜单关联表
 *
 * @author wxm
 * @version 2019-08-01 19:39:34
 * @email xiaomin.wu1@pactera.com
 */
@Service
public class SysRoleMenuService {

    private SysRoleMenuDao sysRoleMenuDao;

    private IPKeyGenerator iPKeyGenerator;

    private SysRoleDao sysRoleDao;

    @Autowired
    private SysMenuDao sysMenuDao;

    private static Pattern pattern = Pattern.compile("\r\n|\r|\n|\n\r");

    @Autowired
    public SysRoleMenuService(SysRoleMenuDao sysRoleMenuDao, IPKeyGenerator iPKeyGenerator, SysRoleDao sysRoleDao) {
        this.sysRoleMenuDao = sysRoleMenuDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.sysRoleDao = sysRoleDao;
    }


    /**
     * 查询角色关联的菜单
     *
     * @param menuListRequest
     * @return
     */
    public JsonResult<List<RoleMenuDto>> menuList(MenuListRequest menuListRequest) {
        List<MenuVo> menuVoList = sysRoleMenuDao.menuList(menuListRequest.getRoleId());
        List<RoleMenuDto> roleMenuDtoList = new ArrayList<>();
        RoleMenuDto roleMenuDto = null;
        for (MenuVo menuVo : menuVoList) {
            roleMenuDto = new RoleMenuDto();
            BeanUtils.copyProperties(menuVo, roleMenuDto);
            roleMenuDtoList.add(roleMenuDto);
        }
        JsonResult<List<RoleMenuDto>> jsonResult = new JsonResult<List<RoleMenuDto>>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(roleMenuDtoList);
        return jsonResult;
    }

    /**
     * 配置角色关联的菜单
     *
     * @param bindMenuRequest
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult bindMenu(BindMenuRequest bindMenuRequest) {
        JsonResult jsonResult = new JsonResult();
        //删除已有菜单
        sysRoleMenuDao.deleteByRoleId(bindMenuRequest.getRoleId(), DateUtil.updateDateStr()
                , UserUtil.getEmployeeNo(), UserUtil.getName());
        //组装菜单
        //角色关联菜单
        List<SysRoleMenu> sysRoleMenuList = generatorSysRoleMenu(bindMenuRequest.getIds(), bindMenuRequest.getRoleId());
        if (!CollectionUtils.isEmpty(sysRoleMenuList)) {
            //批量插入
            sysRoleMenuDao.batchInsert(sysRoleMenuList);
        }
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
        return jsonResult;
    }

    /**
     * 组装SysRoleMenu
     *
     * @param idList
     * @param roleId
     * @return
     */
    private List<SysRoleMenu> generatorSysRoleMenu(Set<String> idList, String roleId) {
        List<SysRoleMenu> SysRoleMenuList = new ArrayList<SysRoleMenu>();
        SysRoleMenu SysRoleMenuTmep = null;
        for (String id : idList) {
            SysRoleMenuTmep = new SysRoleMenu();
            SysRoleMenuTmep.setId(iPKeyGenerator.getGenerateKey());
            SysRoleMenuTmep.setMenuId(id);
            SysRoleMenuTmep.setRoleId(roleId);
            SysRoleMenuTmep.setUpdateDateStr(DateUtil.updateDateStr());
            SysRoleMenuTmep.setCreateBy(UserUtil.getCreateByName());
            SysRoleMenuTmep.setUpdateBy(UserUtil.getUpdateByName());
            SysRoleMenuTmep.setCreateByNo(UserUtil.getCreateByNo());
            SysRoleMenuTmep.setUpdateByNo(UserUtil.getUpdateByNo());
            SysRoleMenuList.add(SysRoleMenuTmep);
        }
        return SysRoleMenuList;
    }

    /**
     * 获取遴选角色的权限
     * @return
     */
    public JsonResult<Set<String>> getCullingAuthUrl() {
        Set<String> cullingAuthUrl = new HashSet<>();
        JsonResult jsonResult = new JsonResult();
        //获取遴选角色
        SysRole sysRoleRequest = new SysRole();
        sysRoleRequest.setCode(Constants.CULLING_ROLE_CODE);
        SysRole sysRole = sysRoleDao.selectOne(sysRoleRequest);
        if(sysRole != null){
            //获取遴选角色的菜单
            List<MenuVo> menuVoList = sysRoleMenuDao.menuList(sysRole.getId());
            cullingAuthUrl = getMenuAuthUrl(menuVoList);
        }
        jsonResult.setData(cullingAuthUrl);
        return jsonResult;

    }

    /**
     * 获取菜单权限URL,SysMenu实体字段auth_url存放菜单权限，auth_url是，相隔的字符串
     * @return
     */
    private Set<String> getMenuAuthUrl(List<MenuVo> menuVoList) {
        Set<String> authUrlSet = new HashSet<String>();
        String authUrlTemp = "";
        for (MenuVo menuVo : menuVoList) {
            authUrlTemp = menuVo.getAuthUrl();
            authUrlSet.addAll(strToSet(authUrlTemp));
        }
        return authUrlSet;
    }

    /**
     * authUrl 为，相隔
     * authUrl转换为set
     *
     * @param authUrl
     * @return
     */
    private Set<String> strToSet(String authUrl) {
        Set<String> authUrlSet = new HashSet<String>();
        if (StringUtils.isEmpty(authUrl)) {
            return authUrlSet;
        }
        String[] authUrls = authUrl.split(",");
        for (String str : authUrls) {
            Matcher m = pattern.matcher(str);
            str = m.replaceAll("");
            authUrlSet.add(str);
        }
        return authUrlSet;
    }

    /**
     * 获取角色下 节点的菜单
     * @param rolePidListRequest
     * @return
     */
    public JsonResult<List<RoleMenuDto>> rolePidList(RolePidListRequest rolePidListRequest) {
        List<MenuVo> menuVoList = sysRoleMenuDao.rolePidList(rolePidListRequest.getRoleId(),rolePidListRequest.getPid(),rolePidListRequest.getPlatform());
        List<RoleMenuDto> roleMenuDtoList = new ArrayList<>();
        RoleMenuDto roleMenuDto = null;
        for (MenuVo menuVo : menuVoList) {
            roleMenuDto = new RoleMenuDto();
            BeanUtils.copyProperties(menuVo, roleMenuDto);
            roleMenuDtoList.add(roleMenuDto);
        }
        JsonResult<List<RoleMenuDto>> jsonResult = new JsonResult<List<RoleMenuDto>>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(roleMenuDtoList);
        return jsonResult;
    }

    /**
     * 角色绑定菜单
     * @param bindMenuRequest
     * @return
     */
    public JsonResult bindMenuNew(BindMenuRequest bindMenuRequest) {
        JsonResult jsonResult = new JsonResult();
        //删除已有菜单
        sysRoleMenuDao.deleteByRoleIdPlatform(bindMenuRequest.getRoleId(), DateUtil.updateDateStr()
                , UserUtil.getEmployeeNo(), UserUtil.getName(),bindMenuRequest.getPlatform());

        //获取菜单的所有子集和菜单的所有父级id
        Set<String> idsAll = new HashSet<>();
        Set<String> ids = bindMenuRequest.getIds();
        for (String id : ids) {
            SysMenu sysMenuTemp = sysMenuDao.selectByPrimaryKey(id);
            List<SysMenu> sysMenuList = sysMenuDao.getSubMenuListAdmin(sysMenuTemp.getParentGroupId(),bindMenuRequest.getPlatform());
            menuIdToSet(idsAll,sysMenuList);
            String parentGroupId = sysMenuTemp.getParentGroupId();
            String[] idSplit = parentGroupId.split("/");
            strIdToSet(idsAll,idSplit);
        }

        //组装菜单
        //角色关联菜单
        List<SysRoleMenu> sysRoleMenuList = generatorSysRoleMenu(idsAll, bindMenuRequest.getRoleId());
        if (!CollectionUtils.isEmpty(sysRoleMenuList)) {
            //批量插入
            sysRoleMenuDao.batchInsert(sysRoleMenuList);
        }
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
        return jsonResult;
    }

    /**
     * 菜单的ID 扔到set
     * @param ids
     * @param sysMenuList
     */
    public void menuIdToSet(Set<String> ids,List<SysMenu> sysMenuList){
        if(CollectionUtils.isEmpty(sysMenuList)){
            return;
        }
        for(SysMenu sysMenu : sysMenuList){
            ids.add(sysMenu.getId());
        }
    }


    /**
     * 菜单的ID 扔到set
     * @param ids
     * @param idSplit
     */
    public void strIdToSet(Set<String> ids,String[] idSplit){
        if(idSplit == null){
            return;
        }
        for(String id : idSplit){
            ids.add(id);
        }
    }

    public static void main(String[] args) {
        String s = "1/101/101101/101101101";
        String[] idSplit = s.split("/");
        System.out.println();
    }
}
